<template>
	<view style="width: 100%;height: 100%;">
		<!--pages/Coupon/Coupon.wxml-->
		<!-- navigationbar -->
		<!-- <view style="width: 100%;background-color: #fff;" :style="{height: statusBarHeight}"></view> -->
       
            <!-- <view style="
                font-weight: 550;
                padding: 0 32rpx;
                height: 88rpx;
                font-size: 35rpx;
                display: flex;
                justify-content: center;
                align-content: center;
                ">
                领券中心
            </view> -->
            <view><uni-status-bar></uni-status-bar></view>

            <view class="search-box flex-cn" >
                <view
                class="navbar-left flex-cn"
                style=" flex: 1;"
                @click="backHome"
                >
                <view style="width:100rpx;text-align: center;" class="qh-rt-single qh-rt-zuo-zuo navbar-back-icon"> </view>
                </view>

                <view style="
                    font-weight: 550;
                    height: 80rpx;
                    line-height: 80rpx;
                    font-size: 35rpx;
                    display: flex;
                    justify-content: center;
                    align-content: center;
                    flex: 1;
                    ">
                    领券中心
                </view>
                <view style="width: 320rpx;flex: 1;"></view>
            </view>

		<view class="navigation-bar"  style="border-radius: 0 0 16rpx 16rpx;">
			<!-- <view style="width: 76rpx;text-align: center; " @tap="backFront">
				<image src="../../static/images/arrow-right-3.png" mode="" class="back-icon" ></image>
			</view> -->

			<view class="navigations">
				<view :class="'navs' +  (nav == 1 ? ' nav-actived' : '')" @tap="changeNav(1)">
					<view class="navH">优惠券</view>
					<view class='underLine' v-if='nav == 1'></view>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view :class="'navs' +  (nav == 4 ? ' nav-actived' : '')" @tap="changeNav(4)"
					v-if="plugPermissionData.wxpaycoupon">
					<view class="navH">微信代金券</view>
					<view class='underLine' v-if='nav == 4'></view>
				</view>
				<view :class="'navs' +  (nav == 3 ? ' nav-actived' : '')" @tap="changeNav(3)"
					v-if="plugPermissionData.shopcoupon">
					<view class="navH">微信商家券</view>
					<view class='underLine' v-if='nav == 3'></view>
				</view>
				<!-- #endif -->
			</view>
		</view>

        <view style="background-color: #f3f3f3;padding-top: 10rpx;">
		<!-- 优惠券 -->
		<block v-if="nav == 1">
			<block v-for="(item, index) in coupon" :key="index" :for-id="index">
				<view class="couponBg">
					<view class="iconfont iconyouhuiquan wxmericon" style="color:#ff8281;"></view>
					<view class="couponBox">
						<view class="left">
							<text>￥</text>
							<text>{{item.reductionmoney}}</text>
						</view>
						<view class="right">
							<text class="title">{{item.coupon_name}}</text>
							<view class="cooupon-mj">
								<text>满{{item.needmoney}}元使用</text>
							</view>
							<view class="stage">{{item.begin_time}}~{{item.end_time}}</view>
							<view :class="'Receive ' + item.bgColor" :id="index" @tap="Receive" :data-btn="item.btn"
								:data-id="item.id">{{item.btn}}</view>
						</view>
					</view>
				</view>
			</block>
			<!-- <view v-if="!coupon" class="empty">暂无优惠券</view> -->
            <view  v-if="!coupon" :style="containerStyle">
                <qh-empty-data 
                text="暂无优惠券~" 
                width="238rpx" 
                height="216rpx" 
                :custom-style="{ marginTop: '40rpx' }"
                ></qh-empty-data>
            </view>
			<view v-else class="nocoupon tips">此处优惠券仅供本店本商城使用</view>
		</block>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 微信代金券 -->
		<block v-if="nav == 4">
			<block v-for="(item, index) in payCoupon" :key="index" :for-id="index">
				<view class="couponBg">
					<view class="iconfont icondaijinquan-03 wxmericon" style="color:#23d2c8;"></view>
					<view class="couponBox" @tap="toCouponDetail(item.id,item.isget,4)">
						<view class="left">
							<view>
								<view>
									<text>￥</text>
									<text style='font-size: 50rpx;font-weight: bold;'>{{item.coupon_amount}}</text>
								</view>
								<view class="cooupon-mj">
									<text>满{{item.transaction_minimum}}元减使用</text>
								</view>
							</view>
						</view>
						<view class="right">
							<view
								style="display: flex;flex-direction: row;justify-content: flex-start;align-items:center">
								<view class="home-coupon-left-icon">
									<!-- <text v-if="item.available_type == 1">线上用</text>
									<text v-else-if="item.available_type == 2">线下用</text -->
									<text>{{item.type_name}}</text>
								</view>
								<view class="title">{{item.stock_name}}</view>
							</view>
							<view class="stage2">{{item.time}}</view>
							<view
								style="font-size: 24rpx;color: #fff;width: 100%;display: flex;justify-content: space-between;align-items: center;">
								<view v-if='item.coupon_type_name'>使用限制:{{item.coupon_type_name}}可用</view>
								<view v-if="item.coupon_type == 2"
									@tap.stop="toProductList(item.goods_id_gather,item.store_id_gather)">查看> </view>
							</view>
							<block
								v-if="(service_status == 2 && item.user_type == 2) || (item.user_type == 1 && item.type == 2  && ordinary_status  == 1)">
								<view class="Receive " style="color: #23d2c8" @tap.stop="showAccount(item.user_type)">
									立即领取</view>
							</block>
							<block v-else>
								<view class="Receive " style="color: #23d2c8" v-if="!item.isget"
									@tap.stop="receivePayCoupon(item.id)">立即领取</view>
								<view class="Receive " style="color: #BBBBBB" v-else>已领取</view>
							</block>
						</view>
					</view>
				</view>
			</block>

            <view  v-if="payCoupon.length ==0" :style="containerStyle" >
                <qh-empty-data 
                text="暂无优惠券~" 
                width="238rpx" 
                height="216rpx" 
                :custom-style="{ marginTop: '40rpx' }"
                ></qh-empty-data>
            </view>
            
			<!-- <view  class="empty">暂无优惠券</view> -->
			<view v-else class="nocoupon tips">此处优惠券仅供本店本商城使用</view>
		</block>

		<!-- 商家券 -->
		<block v-if="nav == 3">
			<block v-for="(item, index) in mercoupon" :key="index" :for-id="index">
				<view class="couponBg">
					<!-- <image src="/static/images/coupon-wx1.png" v-if="item.available_type == 1"></image>
					<image src="/static/images/coupon-wx2.png" v-else-if="item.available_type == 2"></image> -->
					<!-- <image src="/static/images/mercoupon2x.png"></image> -->
					<view class="iconfont iconshangjiaquan wxmericon"></view>
					<view class="couponBox" @tap="toCouponDetail(item.id,item.isget,3)">
						<view class="left">
							<view>
								<view>
									<text>￥</text>
									<text style='font-size: 50rpx;font-weight: bold;'>{{item.discount_amount}}</text>
								</view>
								<view class="cooupon-mj">
									<text>满{{item.transaction_minimum}}元减使用</text>
								</view>
							</view>
						</view>
						<view class="right" style="padding-top: 20rpx;padding-bottom: 10rpx;"
							@tap.stop="getcouponid(item.id)">
							<view
								style="display: flex;flex-direction: row;justify-content: flex-start;align-items:center">
								<view class="home-coupon-left-icon">
									<text v-if="item.available_type == 1">线上用</text>
									<text v-else-if="item.available_type == 2">线下用</text>
									<text v-else>通用</text>
								</view>
								<view class="title">{{item.stock_name}}</view>
							</view>
							<view class="stage2">{{item.available_begin_time}}~{{item.available_end_time}}</view>
							<view
								style="font-size: 24rpx;color: #fff;width: 100%;display: flex;justify-content: space-between;align-items: center;">
								<view>使用限制:{{item.goods_type_name}}可用</view>
								<view v-if="item.goods_type == 2"
									@tap.stop="toProductList(item.goods_id_gather,item.store_id_gather)">查看> </view>
							</view>
							<block
								v-if="(service_status == 2 && item.user_type == 2) || (item.user_type == 1 && item.type == 2  && ordinary_status  == 1)">
								<view class="Receive " style="color: #23D295" @tap="showAccount(item.user_type)">立即领取
								</view>
							</block>
							<block v-else>
								<send-coupon @customevent="getcoupons" :send_coupon_params="item.send_coupon_param"
									:sign="item.sign" :send_coupon_merchant="item.send_coupon_merchant">
									<view class="Receive " style="color: #23D295" v-if="!item.isget">立即领取</view>
									<view class="Receive " style="color: #BBBBBB" v-if="item.isget">已领取</view>
								</send-coupon>
							</block>

						</view>
					</view>
				</view>
			</block>
            <view  v-if="mercoupon.length == 0" :style="containerStyle">
                <qh-empty-data 
                text="暂无优惠券~" 
                width="238rpx" 
                height="216rpx" 
                :custom-style="{ marginTop: '40rpx' }"
                ></qh-empty-data>
            </view>
			<!-- <view v-if="mercoupon.length == 0" class="empty">暂无优惠券</view> -->
			<view v-else class="nocoupon tips">此处优惠券仅供本店本商城使用</view>
		</block>
        </view>
		<!-- #endif -->
	</view>
</template>

<script>
	// pages/Coupon/Coupon.js
	var app = getApp().globalData;

	export default {
		data() {
			return {
				coupon: [],
				bgImg: "/static/images/coupon.png",
				btn: "",
				bgColor: "",
				mercoupon: [], //商家券
				payCoupon: [], //代金券
				nav: 1, //3微信商家券 1优惠券  4微信代金券
				page: 0,
				merpage: 0,
				payPage: 0,
				ismerCoupon: true, //有没有商家券权限
				isPayCoupon: true, //有没有微信代金券权限
				canload: true, //
				isloading: false,
				mercanload: true,
				paycanload: true,
				coupon_id: '',
				// shop_coupon_service: '', //1以获取服务商openid2未获取
				web_url: '', //
				service_status: "",
				ordinary_status: '',
				statusBarHeight: "",
				plugPermissionData: {}
                
                
			};
		},

		components: {},
		props: {},
        computed: {
            containerStyle() {
            // 获取视口高度
            const viewportHeight = wx.getSystemInfoSync().windowHeight;
            const actualHeight = viewportHeight - 44 - 44 - 49; 
            return `height: ${actualHeight}px; display: flex; align-items: center; justify-content: center;`;
            },
        },
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// #ifdef MP-ALIPAY
			if (JSON.stringify(options) == '{}') {
				options = my.getLaunchOptionsSync().query;
			}
			// #endif
			if (options && options.store_id) {
				this.$store.store_id = options.store_id;
			}
			// if(options.genre){
			// 	this.nav = options.genre	
			// }		

			let statusBarHeight = Number(getApp().globalData.XcxData.statusBarHeight) * 2;
			this.statusBarHeight = statusBarHeight + 'rpx';
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: async function() {
			await this.$onLaunched;

			this.getServicePermissions();
			var that = this; //优惠券
			this.mercanload = true;
			this.canload = true;
			this.paycanload = true;
			this.isloading = false;
			this.page = 0;
			this.merpage = 0;
			this.payPage = 0;
			this.payCoupon = [];
			this.mercoupon = [];
			getApp().globalData.sendRequest({
				url: "/Plug/getPlugPermissions",
				data: {},
				success: res => {
					if (res.status == 1) {
						that.plugPermissionData = res.data.plug;
					}
				}
			});
			if (that.nav == 1) {
				that.getcoupan()
			} else {
				that.receivemercoupon()
			}
		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		onShareAppMessage(res) {
			return {
				title: '优惠券',
				path: '/pages/index/Coupon/Coupon?store_id=' + this.$store.store_id + '&share_uid=' +
					app.XcxData.userInfo.uid,
				success: function(res) { // 转发成功
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		onReachBottom() {
			console.log('加载更多', this.nav)
			if (this.nav == 1) {
				this.getcoupan()
			} else if (this.nav == 3 || this.nav == 4) {
				this.receivemercoupon()
			}
		},
		methods: {

            //后退
            backHome() {
                uni.navigateBack();
            },

			//是否通过服务商公众号获取到用户openid
			getServicePermissions() {
				let _this = this;
				getApp().globalData.sendRequest({
					url: "/My/getServiceOpenid",
					data: {},
					success: res => {
						if (res.status == 1) {
							// _this.shop_coupon_service = res.data.shop_coupon_service
							_this.service_status = res.data.service_status;
							_this.ordinary_status = res.data.ordinary_status
						}
					}
				})
			},

			//tab切换 3 商家券 1优惠券
			changeNav(nav) {
				this.nav = nav;
				this.page = 0;
				this.merpage = 0;
				this.payPage = 0;
				this.mercanload = true;
				this.canload = true;
				this.paycanload = true;
				if (nav == 1) {
					this.getcoupan()
				} else if (nav == 3 || nav == 4) {
					this.receivemercoupon()
				}
			},
			//获取优惠券
			getcoupan() {
				let that = this;
				if (that.canload) {
					let page = parseInt(that.page) + 1;
					getApp().globalData.sendRequest({
						url: '/Coupon/coupons',
						type: "post",
						data: {
							coupon_type: 1,
							page: page,
                            store_id: this.$store.mallStoreId
						},
						success: function(res) {
							if (res.status == 1) {
								console.log('11112')
								for (var i = 0; i < res.data.length; i++) {
									if (res.data[i]['collar'] == 0) {
										res.data[i]['bgImg'] = "/static/images/coupon.png";
										res.data[i]['btn'] = '立即领取';
										res.data[i]['bgColor'] = '';
									} else {
										res.data[i]['bgImg'] = "/static/images/coupon.png";
										res.data[i]['btn'] = '已领取';
										res.data[i]['bgColor'] = 'on';
									}
								}
								console.log(page)
								if (page == 1) {
									that.setData({
										coupon: res.data,
										page: page
									});
								} else { //加载更多
									let coupon = that.coupon;
									that.coupon = [...coupon, ...res.data]
									that.setData({
										page: page
									});
								}

								if (res.data.length < 10) {
									that.canload = false
								} else {
									this.canload = true
								}

							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 1500
								})
							}
						}
					})
				} else {
					console.log(that.canLoad)
					// uni.showToast({
					// 	title: "没有更多优惠券了",
					// 	icon: 'none',
					// 	duration: 1500
					// })
				}
			},

			// 立即领取-优惠券
			Receive(e) {
				console.log(e);
				var that = this;
				var id = e.currentTarget.id;
				var coupon_id = e.currentTarget.dataset.id;
				var coupon = this.coupon;
				let couponItem = this.coupon[id];
				let text = e.currentTarget.dataset.btn;
                let store_id = this.$store.mallStoreId
				if (text == '立即领取') {
					uni.showModal({
						content: '确定领取该优惠劵吗？',
						showCancel: true,
						confirmColor: '#ff5c6d',
						success: function(res) {
							// console.log(res);
							if (res.confirm) {
								getApp().globalData.sendRequest({
									url: '/Coupon/collar',
									type: "post",
									data: {
										coupon_id: coupon_id,
                                        store_id
									},
									success: function(res) {
										// console.log(res);
										if (res.status == 1) {
											uni.showToast({
												title: '领取成功',
												duration: 1500,
												mask: true,
												success: function(res) {},
												fail: function(res) {},
												complete: function(res) {}
											});
											couponItem.btn = '已领取';
											couponItem.bgColor = 'on';
											coupon[id] = couponItem
											that.setData({
												coupon: coupon,
                                                couponList:coupon
											}, function() {
                                                console.log('setData success');
                                            });
										} else {
											uni.showToast({
												title: '领取失败',
												duration: 1500,
												mask: true,
												success: function(res) {},
												fail: function(res) {},
												complete: function(res) {}
											});
										}

                                      
									}
								});
							}
						},
						fail: function(res) {},
						complete: function(res) {}
					});

				}
			},

			btnFun() {
				var coupon = this.coupon;

				for (var i = 0; i < coupon.length; i++) {
					coupon[i].btn = '立即领取', coupon[i].bgColor = '';
				}

				this.setData({
					coupon: coupon
				});
			},

			//领取微信代金券
			receivePayCoupon(id) {
				let _this = this;
				getApp().globalData.sendRequest({
					url: "/PayCoupon/receiveCoupon",
					type: "POST",
					data: {
						id: id,
                        store_id: this.$store.mallStoreId
					},
					success: function(res) {

						if (res.status == 1) {
							uni.showToast({
								title: '领取成功',
								icon: 'success',
								duration: 2000
							})
							_this.payCoupon.forEach(function(item, index) {
								if (item.id == id) {
									item.isget = true
								}
							})
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 2000
							})
						}
					}
				})
			},

			//领取商家券,触发冒泡事件拿到该商家券的ID
			getcouponid(id) {
				this.coupon_id = id;
			},

			//获取商家券或者代金券列表
			receivemercoupon() {
				console.log('获取商家券列表')
				let that = this;
				let data = {},
					page;

				data.coupon_type = that.nav;
				if (that.nav == 3) {
					page = parseInt(that.merpage) + 1;
				} else if (that.nav == 4) {
					page = parseInt(that.payPage) + 1;
				}
				data.page = page;
                data.store_id = this.$store.mallStoreId
				if (that.mercanload || that.paycanload) {
					getApp().globalData.sendRequest({
						url: '/Coupon/coupons',
						type: "post",
						data: data,
						success: function(res) {
							// console.log(res);
							if (res.status == 1) {
								that.web_url = res.web_url;
								if (data.page == 1) {
									if (that.nav == 3) {

										let mercoupon = [...res.data];
										mercoupon.forEach(function(item, index) {
											item.isget = false
										})
										that.setData({
											mercoupon: mercoupon,
											merpage: page,

										});
									} else if (that.nav == 4) {
										let payCoupon = [...res.data];
										payCoupon.forEach(function(item, index) {
											item.isget = false
										})
										that.setData({
											payCoupon: payCoupon,
											payPage: page,

										});
									}

								} else { //加载更多
									if (that.nav == 3) {
										//商家券
										let mercoupon = that.mercoupon;
										let data = res.data;
										data.forEach(function(item, index) {
											item.isget = false
										})
										that.mercoupon = [...mercoupon, ...data]
										that.merpage = page
									} else if (that.nav == 4) {
										//代金券
										let payCoupon = that.payCoupon;
										let data = res.data;
										data.forEach(function(item, index) {
											item.isget = false
										})
										that.payCoupon = [...payCoupon, ...data]
										that.payPage = page
									}
								}
								if (that.nav == 3) {
									res.data.length < 10 ? that.mercanload = false : that.mercanload = true;
								} else {
									res.data.length < 10 ? that.paycanload = false : that.paycanload = true;
								}

							} else {
								uni.showToast({
									title: res.message,
									icon: 'none',
									duration: 1500
								})
								if (that.nav == 3) {
									that.setData({
										mercoupon: null
									});
								} else if (that.nav == 4) {
									that.setData({
										payCoupon: null
									});
								}

							}
						}
					});
				} else {
					console.log()
					uni.showToast({
						title: "没有更多券了",
						icon: 'none',
						duration: 1500
					})
				}

			},

			//领券后调用的事件-微信商家券
			getcoupons(params) {
				let _this = this;
				if (params.detail.send_coupon_result[0].code == "SUCCESS") {
					getApp().globalData.sendRequest({
						url: '/ShopCoupon/receiveCouponCallback',
						type: "post",
						data: {
							coupon_id: _this.coupon_id,
							stock_id: params.detail.send_coupon_result[0].stock_id,
							coupon_code: params.detail.send_coupon_result[0].coupon_code,
                            store_id: this.$store.mallStoreId

						},
						success: function(res) {
							uni.showToast({
								title: params.detail.send_coupon_result[0].message,
								duration: 2000
							});
						}
					});
					_this.mercoupon.forEach(function(item, index) {
						if (item.id == _this.coupon_id) {
							item.isget = true
						}
					})
				} else {
					uni.showToast({
						title: params.detail.send_coupon_result[0].message,
						icon: 'none',
						duration: 2000
					});

				}
			},
			//手动返回上一页
			// backFront() {
			// 	uni.navigateBack({
			// 		delta: 1
			// 	})
			// },
			//跳转公众号
			showAccount(type) {
				// + '&xcx_id=1' + 
				let userInfo = uni.getStorageSync('userInfo');
				let uid = userInfo.uid;
				let backPage = getCurrentPages();
				let page = (backPage[backPage.length - 1]).route.toString()
				console.log('this.web_url', userInfo, this.web_url)
				uni.navigateTo({
					url: '../web/web?url=' + this.web_url + '&uid=' + uid + '&page=' + page + '&user_type=' + type
				})
			},

			//部分商品可以用-查看
			toProductList(good_id, store_id) {
				let goods_id_gather = good_id;
				let coupon_type = this.nav == 3 ? 3 : 4;
				uni.navigateTo({
					url: "../../product/productList/productList?goods_id_gather=" + goods_id_gather +
						'&coupon_type=' + coupon_type + '&store_id=' + store_id
				})
			},
			//查看优惠券详情
			toCouponDetail(id, isget, genre) {
				//genre==2 微信代金券 genre==3微信商家券
				uni.navigateTo({
					url: "../merCouponDetail/merCouponDetail?id=" + id + '&type=1' + '&isget=' + isget +
						'&genre=' + genre
				})
			}
		}
	};
</script>
<style>
	@import "./coupon.css";

	/* @import '../../common/iconfont.css'; */
	.navigation-bar {
		width: 100%;
		height: 90rpx;
		/* padding-top: 60rpx; */
		background: #fff;
		display: flex;
		align-items: center;

	}

	.navigations {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.navs {
		width: 30%;
		height: 100%;
		line-height: 80rpx;
		font-size: 28rpx;
		color: #999;
		text-align: center;
		position: relative;
	}

	.nav-actived {
		color: #333;
        border-radius: 16rpx;
        /* border: 1px solid #76BE16; */
	}

	.back-icon {
		width: 20rpx;
		height: 32rpx;
		transform: rotateY(180deg);
		/* */
	}

	.underLine {
		width: 80rpx;
		height: 4rpx;
		border-radius: 4rpx;
		background-color: #76BE16;
		margin: 0 auto;
	}

	.navH {
		height: 72rpx;
	}

	.stage2 {
		font-size: 22rpx;
		color: #fff;
		width: 300rpx;
		margin-bottom: 10rpx;
	}

	.home-coupon-left-icon {
		width: 70rpx;
		height: 28rpx;
		font-size: 18rpx;
		color: #fff;
		/* 	background-image: url(../../../static/images/merCoupon-scene.png); */
		background-image: url(/static/images/merCoupon-scene.png);
		background-size: 100% 100%;
		text-align: center;
		line-height: 23rpx;
		margin-right: 6rpx
	}

	.wxmericon {
		color: #3fd8a3;
		font-size: 182rpx;
	}
</style>
